#!/usr/bin/env python3
#coding=utf-8
#pip3  install    -i https://mirrors.aliyun.com/pypi/simple   aliyun-python-sdk-core aliyunsdkcms

import os
import json
import time
import datetime
import requests
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.acs_exception.exceptions import ClientException
from aliyunsdkcore.acs_exception.exceptions import ServerException
from aliyunsdkcore.auth.credentials import AccessKeyCredential
from aliyunsdkcore.auth.credentials import StsTokenCredential
from aliyunsdkcms.request.v20190101.DescribeSystemEventAttributeRequest import DescribeSystemEventAttributeRequest

# 获取当前时间并往前推 5 分钟（以毫秒为单位）
minutes = 15
time_in_minutes = minutes * 60
now = int(time.time() * 1000)
start_time = now - time_in_minutes * 1000


WEBHOOK_URL = "https://open.larksuite.com/open-apis/bot/v2/hook/ae3051a5-4f37-4468-98f1-ef18caf7bb97"

def send_notification(message, color="red"):
    headers = {"Content-Type": "application/json"}
    template_color = "green" if color == "green" else "red"

    payload = {
        "msg_type": "interactive",
        "card": {
            "config": {
                "wide_screen_mode": True
            },
            "elements": [
                {
                    "tag": "markdown",
                    "content": message,
                }
            ],
            "header": {
                "template": template_color,
                "title": {
                    "content": "云监控API预警",
                    "tag": "plain_text"
                }
            },
        }
    }
    response = requests.post(WEBHOOK_URL, headers=headers, json=payload)
    return response


credentials = AccessKeyCredential(os.environ['ALIBABA_CLOUD_ACCESS_KEY_ID'], os.environ['ALIBABA_CLOUD_ACCESS_KEY_SECRET'])
client = AcsClient(region_id='ap-southeast-1', credential=credentials)

request = DescribeSystemEventAttributeRequest()
request.set_accept_format('json')
request.set_PageNumber(1)
request.set_PageSize(10)
request.set_StartTime(str(start_time))
request.set_Product("eci")
response = client.do_action_with_exception(request)



# 将 bytes 数据转换为字符串并解析为字典
response_dict = json.loads(response.decode('utf-8'))
# 然后就可以根据字典结构来提取具体信息了
system_events = response_dict['SystemEvents']['SystemEvent']
for event in system_events:
    print(f'事件: {event['InstanceName']}   {event['Name']} ')
    # 将时间戳转换为 datetime 对象
    time_obj = datetime.datetime.fromtimestamp(event['Time'] / 1000)
    # 格式化输出时间
    formatted_time = time_obj.strftime('%Y-%m-%d %H:%M:%S')

    message = f"产品: {event['Product']}\n事件名称: {event['Name']}\nPod实例: {event['InstanceName']}\n时间:  {formatted_time}"
    # print(message)
    send_notification(message)